<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <div style="margin-bottom: 20px;">
      <el-button type="primary" size="medium"
      @click="$router.push('/sys-admin/product/brand/add-new')">添加品牌</el-button>
    </div>

    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" width="200" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="pinyin" label="拼音" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="keywords" label="关键词" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column label="是否启用" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
              @change="toggleEnable(scope.row)"
              v-model="scope.row.enable"
              active-color="#13ce66"
              inactive-color="#ccc"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button size="small" icon="el-icon-edit" circle type="primary"
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button size="small" icon="el-icon-delete" circle type="danger"
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px auto;text-align: right;">
      <el-pagination
          @current-change="changePageNum"
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage">
      </el-pagination>
    </div>

    <el-dialog title="编辑品牌" :visible.sync="dialogFormVisible"
               @closed="resetForm('editForm')">
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="130px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="LOGO" prop="logo">
          <el-input v-model="editForm.logo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="editForm.pinyin" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="关键词" prop="keywords">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      dialogFormVisible: false,
      editForm: {
        id: '',
        name: '',
        pinyin: '',
        logo: '',
        description: '',
        keywords: '',
        sort: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序序号', trigger: 'blur' },
          { pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    openEditDialog(brand){
      let url = "http://localhost:9480/brands/"+ brand.id;

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }
      });
    },
    submitEditForm(){
      let url = "http://localhost:9480/brands/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$notify({
            title: '提示',
            message: '编辑品牌成功！'
          });
          this.dialogFormVisible = false;
          this.loadBrandList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadBrandList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    // 切换启用状态
    toggleEnable(brand){
      let enableText = ['禁用', '启用'];
      let urlMethod = ['disable','enable'];
      let enable = brand.enable;
      let url = "http://localhost:9480/brands/" + brand.id + "/" + urlMethod[enable];

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$message.success('将【' + brand.name + '】的启用状态修改为【' + enableText[enable] + '】成功！');
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    openDeleteConfirm(brand) {
      this.$confirm('此操作将永久删除【 ' + brand.id + '-' + brand.name + ' 】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(brand);
      }).catch(() => {
      });
    },
    handleDelete(brand){
      let url = "http://localhost:9480/brands/" + brand.id + "/delete";

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadBrandList();
        }else if(jsonResult.state == 40400){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }else if(jsonResult.state == 40900){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });

    },
    changePageNum(value){
      this.$router.replace("?pageNum="+value);
      this.loadBrandList();
    },
    loadBrandList(){
      let pageNum = this.$router.currentRoute.query.pageNum;
      if(!pageNum){
        pageNum = 1;
      }

      let url = "http://localhost:9480/brands?pageNum="+ pageNum;
      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if(jsonResult.state == 20000){
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        }else{
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadBrandList();
  }
}
</script>